import React, { useEffect, useState } from 'react'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import { getToken } from '@/utils/localStorage'
import {
  Card,
  Table,
  Row,
  Col,
  Form,
  Button,
  Select,
  message,
  Popconfirm,
  Modal,
  Input,
  Upload,
  Icon
} from 'antd'
import {
  queryAppConfigure,
  deleteAppConfigure,
  addAppConfigure
} from '@/services/appConfigure'
const { Option } = Select
const formItemLayout = {
  labelCol: {
    xs: { span: 10 },
    sm: { span: 6 }
  },
  wrapperCol: {
    xs: { span: 10 },
    sm: { span: 16 }
  }
}
const AppConfigure = props => {
  const { getFieldDecorator } = props.form
  const [total, setTotal] = useState(0)
  const [pageInfo, setPageInfo] = useState({
    pageNumber: 1,
    pageSize: 10,
    appType: '' //平台
  })
  const [list, setList] = useState([])
  const [appType, setAppType] = useState('') //平台
  const [visible, setVisible] = useState(false) //模态框
  const styles = {
    spanWidthStyles: {
      width: '70px',
      textAlignLast: 'justify',
      display: 'inline-block'
    },
    formItemStyles: {
      width: '200px'
    }
  }
  useEffect(() => {
    loadList()
  }, [pageInfo])
  const loadList = async () => {
    queryAppConfigure(pageInfo).then(res => {
      setList(res.data.records)
      setTotal(res.data.total)
    })
  }
  const columns = [
    {
      title: '平台',
      dataIndex: 'appType',
      align: 'center',
      render: text => {
        return <span>{text === '01' ? 'ios' : '安卓'}</span>
      }
    },
    {
      title: '版本',
      dataIndex: 'version',
      align: 'center'
    },
    {
      title: '下载地址',
      dataIndex: 'url',
      align: 'center'
    },
    {
      title: '操作',
      dataIndex: 'name4',
      align: 'center',
      render: (text, record) => (
        <span>
          <Popconfirm
            title="您确定要删除吗？"
            cancelText="取消"
            okText="确定"
            onConfirm={() => confirm(record.id)}
            onCancel={cancel}
          >
            <Button type="link" size="small">
              删除
            </Button>
          </Popconfirm>
        </span>
      )
    }
  ]
  const PaginationOptions = {
    current: pageInfo.pageNumber,
    pageSize: pageInfo.pageSize,
    total,
    showTotal: total => {
      return `共${total}条`
    },
    onChange: pageNumber => {
      setPageInfo({ ...pageInfo, pageNumber })
    }
  }
  const onAddBtn = () => {
    setVisible(true)
  }
  //查询
  const onSearchBtn = () => {
    setPageInfo({
      ...pageInfo,
      pageNumber: 1,
      pageSize: 10,
      appType //平台
    })
  }
  const onReset = () => {
    setPageInfo({ ...pageInfo, pageNumber: 1, pageSize: 10 })
    setAppType('')
  }
  const cancel = () => {
    message.warn('您取消了删除动作')
  }
  const confirm = async id => {
    try {
      await deleteAppConfigure({ id: id })
      message.success('删除成功')
      loadList()
    } catch (error) {
      message.warn(error.message)
    }
  }
  const handleOk = () => {
    setVisible(false)
  }
  const handleCancel = () => {
    props.form.resetFields()
    setVisible(false)
  }
  //新增提交
  const onSubmit = e => {
    e.preventDefault()
    props.form.validateFields(async (err, values) => {
      if (!err) {
        const params = values || {}
        for (const key in params) {
          if (typeof params[key] === 'string') {
            params[key] = params[key].trim()
          }
        }

        params.url = imageUrl
        const result = await addAppConfigure({
          ...params
        })
        result.responseType === 'SUCCESS'
          ? message.success('新增成功')
          : message.success(result.errorMessage)
        props.form.resetFields()
        setVisible(false)
        setImageUrl('')
        setFileList([])
        loadList()
      }
    })
  }

  const [imageUrl, setImageUrl] = useState('')
  const [fileList, setFileList] = useState([
    // {
    //   uid: '-4',
    //   name: 'image.png',
    //   status: 'done',
    //   url:
    //     'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'
    // }
  ])

  const handleUploadImage = ({ file, fileList }) => {
    if (file.status === 'done') {
      setFileList(
        fileList.map(item => {
          return {
            uid: fileList.length,
            name: item.name,
            status: 'none',
            url: item.response.data
          }
        })
      )
      setImageUrl(fileList[0].response.data)
    }
    if (file.status) {
      setFileList(fileList)
    }
  }
  return (
    <>
      <PageHeaderWrapper title="APP管理">
        <Card style={{ marginBottom: 20 }}>
          <Row gutter={[5, 20]}>
            <Col span={6}>
              <div>
                <span style={styles.spanWidthStyles}>平台：</span>
                <Select
                  style={styles.formItemStyles}
                  placeholder="请选择"
                  onChange={e => setAppType(e)}
                  value={appType}
                >
                  <Option value="">全部</Option>
                  <Option value="01">IOS</Option>
                  <Option value="02">Android</Option>
                </Select>
              </div>
            </Col>
            <Col span={6} offset={12}>
              <Button type="primary" onClick={onSearchBtn}>
                查询
              </Button>
              <Button type="default" onClick={onReset}>
                重置
              </Button>
              <Button type="primary" onClick={onAddBtn}>
                新增
              </Button>
            </Col>
          </Row>
        </Card>
        <Card>
          <Table
            rowKey="id"
            dataSource={list}
            columns={columns}
            pagination={PaginationOptions}
          />
        </Card>
        <Modal
          title={'新增'}
          visible={visible}
          onOk={handleOk}
          onCancel={handleCancel}
          footer={null}
        >
          <Form {...formItemLayout} onSubmit={onSubmit}>
            <Form.Item label="平台:" hasFeedback>
              {getFieldDecorator('appType', {
                rules: [{ required: true, message: '请选择平台' }]
              })(
                <Select placeholder="请选择平台">
                  <Option value="01">IOS</Option>
                  <Option value="02">Android</Option>
                </Select>
              )}
            </Form.Item>
            <Form.Item label="版本：" hasFeedback>
              {getFieldDecorator('version', {
                rules: [{ required: true, message: '请输入版本！' }]
              })(<Input placeholder="请输入版本" />)}
            </Form.Item>
            {/* <Form.Item label="下载地址：" hasFeedback>
              {getFieldDecorator('url', {
                rules: [{ required: true, message: '请输入下载地址！' }]
              })(<Input placeholder="请输入下载地址" />)}
            </Form.Item> */}
            <Form.Item label="上传文件：" hasFeedback>
              {getFieldDecorator('url', {
                rules: [{ required: true, message: '请先上传文件' }]
              })(
                <Upload
                  accept=""
                  action="/hzsx/busShop/doUpLoadwebp"
                  listType="picture-card"
                  fileList={fileList}
                  headers={{
                    token: getToken()
                  }}
                  onChange={handleUploadImage}
                >
                  {fileList.length > 0 ? (
                    ''
                  ) : (
                    <div>
                      <Icon type="upload" />
                      <div className="ant-upload-text">上传文件</div>
                    </div>
                  )}
                </Upload>
              )}
            </Form.Item>
            {/* 操作按钮区域 */}
            <Row type="flex" justify="center">
              <Button type="info" onClick={handleCancel}>
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                确定
              </Button>
            </Row>
          </Form>
        </Modal>
      </PageHeaderWrapper>
    </>
  )
}
const AppConfigure1 = Form.create({ name: 'AppConfigure-list' })(AppConfigure)
export default AppConfigure1
